package com.zg.paging3.activity.java;

import androidx.paging.PagingSource;
import androidx.paging.PagingState;

import com.zg.paging3.activity.java.model.ArticleBeanInJava;
import com.zg.paging3.activity.java.model.CommonResBody;
import com.zg.paging3.activity.java.model.CommonResList;
import com.zg.paging3.activity.java.model.RetrofitUtil;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import kotlin.coroutines.Continuation;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/***
 * @Author: zxd
 * @CreateDate: 2021/7/9 17:26
 * @Description:
 */
public class MyDataSource extends PagingSource<Integer, ArticleBeanInJava> {
    @Nullable
    @Override
    public Integer getRefreshKey(@NotNull PagingState<Integer, ArticleBeanInJava> pagingState) {
        return 0;
    }

    private LoadResult.Page page1 = null;
    private LoadResult.Error error = null;

    @Nullable
    @Override
    public Object load(@NotNull LoadParams<Integer> loadParams, @NotNull Continuation<? super LoadResult<Integer, ArticleBeanInJava>> continuation) {
        int page = loadParams.getKey();

        Call<CommonResBody<CommonResList<ArticleBeanInJava>>> articleList = RetrofitUtil.getInstance().getArticleList(page);
        articleList.enqueue(new Callback<CommonResBody<CommonResList<ArticleBeanInJava>>>() {
            @Override
            public void onResponse(Call<CommonResBody<CommonResList<ArticleBeanInJava>>> call, Response<CommonResBody<CommonResList<ArticleBeanInJava>>> response) {
                CommonResBody<CommonResList<ArticleBeanInJava>> body = response.body();
                if (body.getData().getCurPage() == 0) {
                    page1 = new LoadResult.Page(body.getData().getDatas(), 0, body.getData().getCurPage() + 1);
                } else {
                    page1 = new LoadResult.Page(body.getData().getDatas(), body.getData().getCurPage(), body.getData().getCurPage() + 1);
                }
            }

            @Override
            public void onFailure(Call<CommonResBody<CommonResList<ArticleBeanInJava>>> call, Throwable t) {
                error = new LoadResult.Error<>(t);
            }
        });
        if (page1 == null)
            return error;
        else
            return page1;
    }
}
